package liquidfs.data.ops;

import java.io.*;

import liquidfs.*;
import liquidfs.core.*;
import liquidfs.data.*;
import liquidfs.data.ex.*;
import liquidfs.data.ex.FileNotFoundException;
import liquidfs.data.fs.*;

public class QueryObjectInformationOperation extends AbstractFileOperation<LiquidObject> {
   
	public QueryObjectInformationOperation(PeerDevice origin, String filepath) {
		super(origin, filepath);
	}

	@Override
	public LiquidObject execute(Application app, InputStream in, OutputStream out) {
	   
	   // Get a reference to the file system
		LiquidFileSystem fs = app.getFileSystem();
		
		// If the file is on the file system, do it here
		if (fs.isLocal(this.getFilePath())) {
   		return fs.getPath(this.getFilePath());
		}

		// Iterate through each device we're connected two, except the ones that have already been queried
		for (Link link : app.getConfiguration().getLinks()) {
		
		   // Skip devices that have already been queried
		   if (this.reached(link.getDevice())) {
		      continue;
		   }
		   
   		// Pass this message along to other links in the network
   		Result<LiquidObject> result = fs.relay(link, this, null, null);
   		LiquidObject remoteCache;
   		
   		// Get the contents; if this device had nothing to add, skip it
   		try {
   		   remoteCache = result.getData();
   		}
   		catch (FileSystemException e) {
   		   continue;
   		}
   		
   		return remoteCache;
		}
		   
		throw new FileNotFoundException("Unable to find the file " + this.getFilePath() + ".");
		
	}

}
